from django.shortcuts import render
from django.http import JsonResponse, Http404
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend

from article.filters import ArticleTitleFilter
from article.permissions import IsAdminUserOrReadOnly
from article.serializers import AvatarSerializer, ArticleDetailSerializer, ArticleSerializer, CategorySerializer, \
    CategoryDetailSerializer, TagSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response

# Create your views here.
from article.models import Article, Category, Tag, Avatar
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import filters


# class ArticleList(generics.ListCreateAPIView):
#     permission_classes = [IsAdminUserOrReadOnly, ]
#     queryset = Article.objects.all()
#     serializer_class = ArticleListSerializer
#
#     def perform_create(self, serializer):
#         serializer.save(author=self.request.user)
#
#
# class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
#     permission_classes = [IsAdminUserOrReadOnly, ]
#     queryset = Article.objects.all()
#     serializer_class = ArticleDetailSerializer


class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    permission_classes = [IsAdminUserOrReadOnly, ]
    # filter_class = ArticleTitleFilter
    # filter_backends = [DjangoFilterBackend, ]
    # filter_fields = ['author__username', 'title']
    filter_backends = [filters.SearchFilter, ]
    search_fields = ['title', ]

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def get_serializer_class(self):
        if self.action == 'list':
            return ArticleSerializer
        else:
            return ArticleDetailSerializer

    # def get_queryset(self):
    #     queryset = self.queryset
    #     username = self.request.query_params.get('username', None)
    #
    #     if username is not None:
    #         queryset = queryset.filtername(author__username=username)
    #
    #     return queryset


class CategoryViewSet(viewsets.ModelViewSet):
    """分类视图集"""
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUserOrReadOnly, ]

    def get_serializer_class(self):
        if self.action == 'list':
            return CategorySerializer
        else:
            return CategoryDetailSerializer


class TagViewSet(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [IsAdminUserOrReadOnly]


class AvatarViewSet(viewsets.ModelViewSet):
    queryset = Avatar.objects.all()
    serializer_class = AvatarSerializer
    permission_classes = [IsAdminUserOrReadOnly]